package mysql

import (
	"go-ddd-ecommerce/internal/domain/user"
	"time"

	"github.com/google/uuid"

	"gorm.io/gorm"
)

// 基础设施层实现仓储层的接口
type userModel struct {
	// Id因为修改成了uuid，所以就不组合gorm的字段进来了
	Id string `gorm:"column:id;primaryKey"`
	// 用户名
	Username string `gorm:"unique;not null" json:"username"`
	// 密码
	Password string `gorm:"not null" json:"-"`
	// 账户金额
	Balance float64 `gorm:"not null;default:0" json:"balance"`

	// GORM 管理字段
	CreatedAt time.Time
	UpdatedAt time.Time
	DeletedAt gorm.DeletedAt `gorm:"index"`
}

// TableName 指定表名
func (userModel) TableName() string {
	return "users"
}

// ToDomain 映射成领域模型
func (u *userModel) ToDomain() *user.User {
	return &user.User{
		ID:       uuid.MustParse(u.Id),
		Username: u.Username,
		Password: u.Password,
		Balance:  u.Balance,
	}
}

func userToUserModel(user *user.User) *userModel {
	return &userModel{
		Id:       user.ID.String(),
		Username: user.Username,
		Password: user.Password,
		Balance:  user.Balance,
	}
}

type UserRepository struct {
	db *gorm.DB
}

func NewUserRepository(db *gorm.DB) *UserRepository {
	return &UserRepository{
		db: db,
	}
}

func (r *UserRepository) FindByID(id uuid.UUID) (*user.User, error) {
	var user userModel
	if err := r.db.Where("id = ?", id.String()).First(&user).Error; err != nil {
		return nil, err
	}
	return user.ToDomain(), nil
}

func (r *UserRepository) FindByUsername(username string) (*user.User, error) {
	var user userModel
	result := r.db.Where("username = ?", username).First(&user)
	if result.Error != nil {
		return nil, result.Error
	}
	return user.ToDomain(), nil
}

func (r *UserRepository) Save(user *user.User) error {
	return r.db.Create(userToUserModel(user)).Error
}

func (r *UserRepository) Update(user *user.User) error {
	return r.db.Updates(userToUserModel(user)).Error
}

//func (r *UserRepository) Delete(id uuid.UUID) error {
//	return r.db.Delete(&userModel{}, id.String()).Error
//}
